package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.PurchaseOrderQueryDTO;
import com.intelligent.mapper.PurchaseOrderMapper;
import com.intelligent.mapper.PurchaseSupplierMapper;
import com.intelligent.pojo.PurchaseOrder;
import com.intelligent.pojo.PurchaseSupplier;
import com.intelligent.service.PurchaseOrderService;
import com.intelligent.vo.PurchaseOrderVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
* @author 86188
* @description 针对表【purchase_order(采购订单信息表)】的数据库操作Service实现
* @createDate 2025-08-29 11:59:52
*/
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder>
    implements PurchaseOrderService {

    @Autowired
    private PurchaseSupplierMapper purchaseSupplierMapper;

    private static final String ORDER_NO_PREFIX = "CG";

    @Override
    public IPage<PurchaseOrderVO> queryPage(PurchaseOrderQueryDTO queryDTO, Integer pageNum, Integer pageSize) {
        // 1. 构建分页对象
        Page<PurchaseOrder> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        LambdaQueryWrapper<PurchaseOrder> queryWrapper = new LambdaQueryWrapper<>();

        // 订单号模糊查询
        if (StringUtils.isNotBlank(queryDTO.getOrderNo())) {
            queryWrapper.like(PurchaseOrder::getOrderNo, queryDTO.getOrderNo());
        }

        // 采购类型查询
        if (queryDTO.getPurchaseType() != null) {
            queryWrapper.eq(PurchaseOrder::getPurchaseType, queryDTO.getPurchaseType());
        }

        // 入库状态查询
        if (queryDTO.getStorageStatus() != null) {
            queryWrapper.eq(PurchaseOrder::getStorageStatus, queryDTO.getStorageStatus());
        }

        // 付款状态查询
        if (queryDTO.getPaymentStatus() != null) {
            queryWrapper.eq(PurchaseOrder::getPaymentStatus, queryDTO.getPaymentStatus());
        }

        // 3. 执行分页查询
        IPage<PurchaseOrder> orderPage = this.page(page, queryWrapper);

        // 4. 转换为VO对象并填充额外信息
        return orderPage.convert(this::convertToVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createPurchaseOrder(PurchaseOrder purchaseOrder) {
        // 1. 参数校验
        validatePurchaseOrder(purchaseOrder);

        // 2. 生成订单号
        purchaseOrder.setOrderNo(generateOrderNo());

        // 3. 设置默认值
        if (purchaseOrder.getStorageStatus() == null) {
            purchaseOrder.setStorageStatus(0); // 默认待入库
        }
        if (purchaseOrder.getPaymentStatus() == null) {
            purchaseOrder.setPaymentStatus(0); // 默认待付款
        }

        // 4. 保存采购订单
        boolean saved = this.save(purchaseOrder);

        return saved;
    }

    @Override
    public String generateOrderNo() {
        // 格式：CG + yyyyMMdd + 4位随机数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String randomNum = String.format("%04d", ThreadLocalRandom.current().nextInt(10000));
        return ORDER_NO_PREFIX + dateStr + randomNum;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePurchaseOrder(PurchaseOrder purchaseOrder) {
        if (purchaseOrder == null || purchaseOrder.getId() == null) {
            throw new IllegalArgumentException("ID不能为空");
        }
        validatePurchaseOrder(purchaseOrder);
        return this.updateById(purchaseOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return true;
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<PurchaseOrderVO> queryList(PurchaseOrderQueryDTO queryDTO) {
        LambdaQueryWrapper<PurchaseOrder> queryWrapper = new LambdaQueryWrapper<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(queryDTO.getOrderNo())) {
            queryWrapper.like(PurchaseOrder::getOrderNo, queryDTO.getOrderNo());
        }
        if (queryDTO.getPurchaseType() != null) {
            queryWrapper.eq(PurchaseOrder::getPurchaseType, queryDTO.getPurchaseType());
        }
        if (queryDTO.getStorageStatus() != null) {
            queryWrapper.eq(PurchaseOrder::getStorageStatus, queryDTO.getStorageStatus());
        }
        if (queryDTO.getPaymentStatus() != null) {
            queryWrapper.eq(PurchaseOrder::getPaymentStatus, queryDTO.getPaymentStatus());
        }
        List<PurchaseOrder> list = this.list(queryWrapper);
        return list.stream().map(this::convertToVO).collect(java.util.stream.Collectors.toList());
    }

    /**
     * 将PurchaseOrder转换为PurchaseOrderVO
     */
    private PurchaseOrderVO convertToVO(PurchaseOrder order) {
        if (order == null) {
            return null;
        }

        PurchaseOrderVO vo = new PurchaseOrderVO();
        BeanUtils.copyProperties(order, vo);

        // 设置供应商信息
        if (order.getSupplierId() != null) {
            PurchaseSupplier supplier = purchaseSupplierMapper.selectById(order.getSupplierId());
            if (supplier != null) {
                vo.setSupplierName(supplier.getSupplierName());
                vo.setSupplierCode(supplier.getSupplierCode());
            }
        }

        // 设置状态名称
        vo.setPurchaseTypeName(getPurchaseTypeName(order.getPurchaseType()));
        vo.setStorageStatusName(getStorageStatusName(order.getStorageStatus()));
        vo.setPaymentStatusName(getPaymentStatusName(order.getPaymentStatus()));

        // 查询已入库数量和已支付金额
        calculateStoredAndPaidInfo(vo);

        return vo;
    }

    /**
     * 验证采购订单参数
     */
    private void validatePurchaseOrder(PurchaseOrder purchaseOrder) {
        if (purchaseOrder == null) {
            throw new IllegalArgumentException("采购订单信息不能为空");
        }
        if (purchaseOrder.getSupplierId() == null) {
            throw new IllegalArgumentException("供应商不能为空");
        }
        if (purchaseOrder.getPurchaseType() == null) {
            throw new IllegalArgumentException("采购类型不能为空");
        }
        if (purchaseOrder.getExpectedStorageTime() == null) {
            throw new IllegalArgumentException("期望入库时间不能为空");
        }
        if (purchaseOrder.getPurchaseQuantity() == null || purchaseOrder.getPurchaseQuantity() <= 0) {
            throw new IllegalArgumentException("采购数量必须大于0");
        }
        if (purchaseOrder.getPurchaseAmount() == null || purchaseOrder.getPurchaseAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("采购金额必须大于0");
        }
    }

    /**
     * 计算已入库数量和已支付金额
     */
    private void calculateStoredAndPaidInfo(PurchaseOrderVO vo) {
        // 这里需要根据实际业务实现查询已入库数量和已支付金额的逻辑
        // 示例代码，需要根据实际表结构调整
        vo.setStoredQuantity(0);
        vo.setPaidAmount(BigDecimal.ZERO);
    }

    /**
     * 获取采购类型名称
     */
    private String getPurchaseTypeName(Integer type) {
        if (type == null) {
            return "";
        }
        switch (type) {
            case 0: return "生产采购";
            case 1: return "备货采购";
            default: return "其他类型";
        }
    }

    /**
     * 获取入库状态名称
     */
    private String getStorageStatusName(Integer status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case 0: return "待入库";
            case 1: return "部分入库";
            case 2: return "全部入库";
            default: return "未知状态";
        }
    }

    /**
     * 获取付款状态名称
     */
    private String getPaymentStatusName(Integer status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case 0: return "待付款";
            case 1: return "部分付款";
            case 2: return "已付款";
            case 3: return "已退货";
            default: return "未知状态";
        }
    }
}
